package 反射4;
/*
@Date:2025/3/17
*/

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflectionDemo {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        //不使用反射
        final Teacher teacher = new Teacher();
        final String typelnstanceof = getTypelnstanceof(teacher);
        System.out.println("typelnstanceof = " + typelnstanceof);
//测试反射方式
        final Student student = new Student();
        final String type = getType(student);
        System.out.println("type = " + type);


    }
    public static String  getTypelnstanceof(Object obj){
        //学生
        if(obj instanceof Student){
            final Student student = (Student) obj;
            final String userType = student.getUserType("王小明");
            return userType;
        }
        //老师
        if(obj instanceof Teacher){
            final Teacher teacher = (Teacher) obj;
            final String userType = teacher.getUserType("王笑笑");
            return userType;
        }
        return null;
    }
    //通过反射获取用户类型
    public static String getType(Object obj) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        final Class<?> aClass = obj.getClass();
        final Object o = aClass.newInstance();
        final Method getUserType = aClass.getMethod("getUserType", String.class);
        String invoke =(String) getUserType.invoke(o, "王笑笑");
        return  invoke;



    }
}
